﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using BoYuanCore.DBServices.Base;
using BoYuanCore.Framework.Extensions;
using BoYuanCore.Framework.Net;
using Microsoft.AspNetCore.Http;

namespace BoYuanCore.DBServices
{
    public class SysLoginLog
    {
        /// <summary>
        /// 添加登录日志
        /// </summary>
        /// <param name="username"></param>
        /// <param name="pwd"></param>
        /// <param name="loginState"></param>
        /// <param name="remark"></param>
        /// <param name="userid"></param>
        public static async Task<bool> AddLoginLogAsync(string username, string pwd, Entities.EnumClass.SysLoginLog.LoginState loginState, string remark = "", long userid = 0)
        {
            //如果不需要登录日志功能，请
            //return false;

            Entities.SysLoginLog log = new Entities.SysLoginLog();
            log.UserName = username.ToMaxLengthString(100);
            log.LoginState = loginState;
            if (loginState != Entities.EnumClass.SysLoginLog.LoginState.登录成功)
            {
                log.PwdShow = pwd.ToMaxLengthString(100);
                log.UserId = 0;
            }
            else
            {
                log.PwdShow = string.Empty;
                log.UserId = userid;
            }
            HttpContextAccessor context = new HttpContextAccessor();

            log.Addtime = DateTime.Now;
            log.IP = HttpHelper.GetTrueUserIP().ToMaxLengthString(500);
            log.UserAgent = context.HttpContext.Request.Headers["User-Agent"].ToString().ToMaxLengthString(300);
            log.LoginChannel = Entities.EnumClass.SysLoginLog.LoginChannel.PC;//默认都是pc登录
            log.Remark = remark;

            //解析 User-Agent可以参考 https://www.coderbusy.com/archives/732.html 。 这里不做解析

            var fsql = FreeSqlHelper.Fsql;
            return await fsql.Insert(log).ExecuteAffrowsAsync()> 0;
        }
    }
}
